<template>
  <base-breadcrumb>
    <!-- 表单 -->
    <a-card class="FromButton">
      <title-name title="基本信息" />
      <a-form-model
        ref="form"
        :model="formInfo"
        :rules="rules"
        hide-required-mark
      >
        <a-row :gutter="24">
          <a-col
            :md="16"
            :sm="16"
          >
            <a-form-model-item
              label="所属单位"
              :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              prop="projectId"
            >
              <org-tree-select
                v-model="formInfo.projectId"
                is-auto-select-first
                :is-query-projec-detail="false"
                is-need-auth
                check-strictly
                @handleChange="handleProChanged"
                @select="selectOrg"
              />
            </a-form-model-item>
          </a-col>
          <!--          <a-col :md="8" :sm="8">-->
          <!--            <a-form-model-item-->
          <!--              label="所属分公司"-->
          <!--              :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"-->
          <!--              :wrapperCol="{ lg: { span: 15 }, sm: { span: 15 } }"-->
          <!--              prop="branchComId"-->
          <!--            >-->
          <!--              <SelectSubCompany placeholder="请选择" v-model="formInfo.branchComId"></SelectSubCompany>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :md="8" :sm="8">-->
          <!--            <a-form-model-item-->
          <!--              label="所属项目"-->
          <!--              :labelCol="{ lg: { span: 5 }, sm: { span: 5 } }"-->
          <!--              :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"-->
          <!--              prop="projectId"-->
          <!--            >-->
          <!--              <SelectProject-->
          <!--                placeholder="请选择"-->
          <!--                v-model="formInfo.projectId"-->
          <!--                :form="formInfo"-->
          <!--                :isClear="true"-->
          <!--                keyValue="branchComId"-->
          <!--                ref="selectProject"-->
          <!--                @change="handleProChanged"-->
          <!--              ></SelectProject>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="名称"
              :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
            >
              <BaseInput
                v-model="formInfo.projectTitle"
                disabled
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <span style="color: red">注：每年6月和12月各上报一次</span>
    </a-card>
    <!-- 表格 -->
    <!-- 一级表格 -->
    <a-card>
      <div
        v-if="typeYear != ''"
        class="table-operator"
      >
        <title-name title="优化统计项" />
        <a-button
          type="primary"
          @click="handleUpdateItem('add')"
        >
          添加优化项
        </a-button>
        <ExcelImportButton
          ref="excelImportButton"
          icon="import"
          button-text="导入"
          @handleSubmit="handleImport"
        />
        <ExportExcel
          ref="exportExcel"
          :export-list="exportList"
          icon="export"
          :file-name="'钢筋技术优化模板.xlsx'"
          button-text="下载模板"
        />
      </div>
      <a-table
        row-key="id"
        :data-source="formInfo.optimizations"
        :pagination="false"
        :columns="typeYear == '下半年' ? columnsSecond : columnsFirst"
        bordered
      >
        <span
          slot="description"
          slot-scope="text"
        >
          <ellipsis
            :length="8"
            tooltip
          >{{ text }}</ellipsis>
        </span>
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <!-- 操作 -->
        <span
          v-if="isShow"
          slot="operation"
          slot-scope="text, record, index"
        >
          <a @click="handleUpdateItem('edit', index)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="确定要删除?"
            @confirm="() => handleUpdateItem('delete', index)"
          >
            <a>删除</a>
          </a-popconfirm>
          <!-- <a @click="handleUpdateItem('delete', index)">删除</a> -->
        </span>
      </a-table>
    </a-card>
    <a-card>
      <!-- 相关附件 -->
      <div class="mb20">
        <title-name title="相关附件" />
        <upload-list
          :business-code="'TM04'"
          :upload-arrys.sync="formInfo.reviewFileInfoVOList"
          multiple
          @fileArrysData="handleFileUploaded"
        />
      </div>
    </a-card>
    <div class="tool-btns page-btn-right-top">
      <!-- <a-button v-if="this.$route.query.isShow" type="primary" @click="preservation">基本信息保存</a-button>
      <a-button v-if="this.$route.query.isShow" type="primary" @click="addSubmit(true)" class="ml12">提交</a-button> -->
      <a-button
        v-if="isShow && formInfo.auditStatus == 'DRAFT'"
        class="ml12"
        type="danger"
        @click="discard(formInfo)"
      >
        删除草稿
      </a-button>
      <a-button
        v-if="isShow"
        class="ml12"
        type="primary"
        :loading="loading['DRAFT']"
        @click="handleSave('DRAFT')"
      >
        保存草稿
      </a-button>
      <a-button
        v-if="isShow"
        type="primary"
        :loading="loading['SUBMITTED']"
        class="ml12"
        @click="handleSave('SUBMITTED')"
      >
        提交
      </a-button>

      <a-button
        type="primary"
        class="ml12"
        @click="backs"
      >
        关闭
      </a-button>
    </div>
    <!-- 子组件 -->
    <editFrom
      :visible="visible"
      :type-year="typeYear"
      :model="childInitData"
      @ok="handleOk"
      @cancel="handleCancel"
    />
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
  </base-breadcrumb>
</template>
<script>
import UploadList from '@/components/UploadList'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import { addSteel, updateSteel, getSteelDetail, tableDelete, print } from '@/api/technologySteel'
import editFrom from './editFrom.vue'
import { formData } from '@/views/materials/equipmentPurchasePlan/components/insideModel'
import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
const columnsFirst = [
  {
    title: '序号',
    width: '100px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '钢筋技术优化名称',
    dataIndex: 'name'
  },
  {
    title: '钢筋技术优化量（t）',
    dataIndex: 'optimizationAmount'
  },
  {
    title: '上半年钢筋工程使用总量（t）',
    dataIndex: 'engineeringAmount'
  },
  {
    title: '钢筋技术优化效益（万元）',
    dataIndex: 'optimizationBenefit'
  },
  {
    title: '上半年钢筋工程总造价（万元）',
    dataIndex: 'engineeringPrice'
  },
  {
    title: '钢筋技术优化效益率（%）',
    dataIndex: 'optimizationRate'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '120px',
    // fixed: 'right',
    scopedSlots: { customRender: 'operation' }
  }
]
const columnsSecond = [
  {
    title: '序号',
    width: '100px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '钢筋技术优化名称',
    dataIndex: 'name'
  },
  {
    title: '钢筋技术优化量（t）',
    dataIndex: 'optimizationAmount'
  },
  {
    title: '下半年钢筋工程使用总量（t）',
    dataIndex: 'engineeringAmount'
  },
  {
    title: '钢筋技术优化效益（万元）',
    dataIndex: 'optimizationBenefit'
  },
  {
    title: '下半年钢筋工程总造价（万元）',
    dataIndex: 'engineeringPrice'
  },
  {
    title: '钢筋技术优化效益率（%）',
    dataIndex: 'optimizationRate'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '120px',
    // fixed: 'right',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  name: 'a' + Date.now(),
  components: {
    editFrom,
    SelectSubCompany,
    SelectProject,
    UploadList,
    ExportExcel,
    BasePrintButton
  },
  data() {
    this.columnsFirst = columnsFirst
    this.columnsSecond = columnsSecond
    return {
      // checkVisibleInDetail: checkVisibleInDetail(this),
      loading: {
        DRAFT: false,
        SUBMITTED: false
      },
      childInitData: {},
      formInfo: {
        branchComId: '',
        projectId: '',
        projectTitle: '',
        optimizations: [],
        reviewFileInfoVOList: []
      },
      rules: {
        branchComId: [{ required: true, message: '请选择', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      typeYear: '',
      visible: false,
      routeObj: '', //接收跳转带过来的值
      dataSource: [],
      isShow: this.$route.query.isShow,
      pageFlag: this.$route.query.pageFlag,
      id: '',
      importCheck1: {
        钢筋技术优化名称: 'name',
        '钢筋技术优化量（t）': 'optimizationAmount',
        '上半年钢筋工程使用总量（t）': 'engineeringAmount',
        '钢筋技术优化效益（万元）': 'optimizationBenefit',
        '上半年钢筋工程总造价（万元）': 'engineeringPrice'
      }, // 导入字段对应
      importCheck2: {
        钢筋技术优化名称: 'name',
        '钢筋技术优化量（t）': 'optimizationAmount',
        '下半年钢筋工程使用总量（t）': 'engineeringAmount',
        '钢筋技术优化效益（万元）': 'optimizationBenefit',
        '下半年钢筋工程总造价（万元）': 'engineeringPrice'
      }, // 导入字段对应
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async created() {
    this.getSteelDetail()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('technology_reinforcement_lean_management')
  },
  computed: {
    exportList() {
      let list1 = this.$clone(this.columnsFirst)
      let list2 = this.$clone(this.columnsSecond)
      list1.pop()
      list1.pop()
      list1.shift()
      list2.pop()
      list2.pop()
      list2.shift()
      return [
        {
          columns: this.typeYear == '下半年' ? list2 : list1,
          datas: [{}]
        }
      ]
    }
  },

  methods: {
    selectOrg(val) {
      this.formInfo.branchComId = val[val.length - 2].orgId
    },
    handleImport(e) {
      let form = []
      let that = this
      let importCheck = this.typeYear == '下半年' ? this.importCheck2 : this.importCheck1
      let messages = []
      for (let m in e) {
        let keys = e[m]
        let listItem = {}
        let msg = `第${Number(m) + 1}行：`
        let msgList = []
        // 校验excel的表头数量
        // console.log(e[m],e[m][index])
        // 校验excel的表头字段
        for (let i in importCheck) {
          let item = importCheck[i]
          if (!keys[i] && !Object.keys(keys).includes(i) && i != '备注') {
            msgList.push(`${i.replace(/\*/g, '')}不能为空`)
          } else {
            // 校验数字
            if (
              (item === 'optimizationAmount' ||
                item === 'engineeringAmount' ||
                item === 'optimizationBenefit' ||
                item === 'engineeringPrice') &&
              !this.isNumber(keys[i])
            ) {
              msgList.push(`${i.replace(/\*/g, '')}格式为数字`)
            } else {
              listItem[item] = keys[i]
            }
          }
        }
        console.log(listItem)
        if (listItem.engineeringAmount < listItem.optimizationAmount) {
          msgList.push(`钢筋技术优化量不能大于${this.typeYear}钢筋工程使用总量`)
        }
        if (listItem.engineeringPrice < listItem.optimizationBenefit) {
          msgList.push(`钢筋技术优化效益不能大于${this.typeYear}钢筋工程总造价`)
        }
        if (
          this.formInfo.optimizations.length > 0 &&
          listItem.engineeringAmount != this.formInfo.optimizations[0].engineeringAmount
        ) {
          msgList.push(`导入的${this.typeYear}钢筋工程使用总量与表格中不一致`)
        }
        if (
          this.formInfo.optimizations.length > 0 &&
          listItem.engineeringPrice != this.formInfo.optimizations[0].engineeringPrice
        ) {
          msgList.push(`导入的${this.typeYear}钢筋工程总造价与表格中不一致`)
        }
        if (form.length > 0 && listItem.engineeringAmount != form[0].engineeringAmount) {
          msgList.push(`导入的${this.typeYear}钢筋工程使用总量与第一行不一致`)
        }
        if (form.length > 0 && listItem.engineeringPrice != form[0].engineeringPrice) {
          msgList.push(`导入的${this.typeYear}钢筋工程总造价与第一行不一致`)
        }
        msgList.length > 0 && messages.push(<div>{msg + msgList.join('，')}</div>)
        form.push(listItem)
      }
      if (messages.length > 0) {
        that.loadingImport = false
        let content = messages.map(item => <div style="width:100%">{item}</div>)
        that.$warning({
          width: 800,
          title: '导入失败',
          content: content
        })
        return
      }

      form.forEach(i => {
        if (!i.engineeringPrice || i.engineeringPrice == 0) i.optimizationRate = '0.00'
        const result = (i.optimizationBenefit / i.engineeringPrice) * 100
        i.optimizationRate = isNaN(result) ? '0.00' : result.toFixed(2)
      })

      this.formInfo.optimizations = this.formInfo.optimizations.concat(form)
    },
    /**
     * 字符串/数字判断
     */
    isNumber(val) {
      let regPos = /^\d+(\.\d+)?$/ //非负浮点数
      let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/ //负浮点数
      if (regPos.test(val) || regNeg.test(val)) {
        return true
      } else {
        return false
      }
    },
    discard(record) {
      let _this = this
      this.$confirm({
        title: '温馨提示',
        content: '确定是否删除数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return tableDelete({ id: record.id }).then(res => {
            _this.$message.success('删除成功')
            _this.backs()
          })
        },
        onCancel() {}
      })
    },
    getSteelDetail() {
      const id = this.$route.query.id
      if (id) {
        getSteelDetail(id).then(res => {
          if (res.code === 200 || res.data.code === 200) {
            this.formInfo = { ...res.data, reviewFileInfoVOList: res.data.reviewFileInfoVOList || [] }
            this.$nextTick(() => {
              this.formInfo.projectId = res.data.projectId
              this.typeYear = this.formInfo.projectTitle.slice(5, 8)
            })
          }
        })
      } else {
        this.handleProChanged()
      }
    },
    // 处理优化项的操作
    handleUpdateItem(type, itemIndex = -1) {
      const { optimizations } = this.formInfo
      const actionMap = {
        add: () => {
          this.childInitData = {}
          if (optimizations.length > 0) {
            this.childInitData = {
              engineeringAmount: optimizations[0].engineeringAmount,
              engineeringPrice: optimizations[0].engineeringPrice,
              disabled: true
            }
          }
          this.visible = true
        },
        edit: () => {
          this.childInitData = { ...optimizations[itemIndex], updateIndex: itemIndex, disabled: true }
          this.visible = true
        },
        delete: () => {
          optimizations.splice(itemIndex, 1)
        }
      }
      actionMap[type] && actionMap[type]()
    },
    handleSave(status) {
       this.setProcessConfig = null;
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.loading[status]) return
        this.loading[status] = true
        const params = {
          ...this.formInfo,
          auditStatus: status
        }
        if (params.reviewFileInfoVOList?.length<1){
          this.loading[status] = false
          this.$message.warning('请选择上传相关附件')
          return
        }
        const fn = this.pageFlag == 'add' ? addSteel : updateSteel
        this.submitApprovalConfirm(status =='SUBMITTED' ? this.processConfig : 6, (flag)=>{
          if(!flag) {
            this.loading[status] = false
            return
          }
          fn(params)
                  .then(res => {
                    this.loading[status] = false
                    if (res.code === 200 || res.data.code === 200) {
                      this.$message.success('成功')
                      if(status =='SUBMITTED') {
                        //提交时，返回id
                        this.businessId = res.data.id;
                        this.setProcessConfig = this.processConfig;
                        return
                      }else{
                        this.backs()
                      }
                    }
                  })
                  .catch(err => {
                    this.loading[status] = false
                  })
        })

      })
    },
    handleFileUploaded(list) {
      this.formInfo.reviewFileInfoVOList = [...list]
    },
    handleProChanged() {
      //   const projectName = this.$refs.selectProject.getValueName(this.formInfo.projectId)
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      this.formInfo.projectTitle = `${year}年${month > 6 ? '下半' : '上半'}年钢筋优化率`
      console.log(this.formInfo.projectTitle)
      this.typeYear = this.formInfo.projectTitle.slice(5, 8)
    },
    // 关闭按钮
    backs() {
      this.$multiTab.close(this.$route.fullpath)
    },
    // 传值控制弹窗开关
    handleCancel() {
      this.visible = false
    },
    // 接收到子组件输入框中的值
    handleOk(data) {
      this.visible = false
      const { optimizations } = this.formInfo
      const { updateIndex } = data
      if (updateIndex > -1) {
        optimizations.splice(updateIndex, 1, { ...data })
      } else {
        optimizations.push({ ...data })
      }
    }
  }
}
</script>
